package server.jobs;

import static server.db.StmtHelper.db;
import it.sauronsoftware.cron4j.Scheduler;
import it.sauronsoftware.cron4j.TaskCollector;

import java.io.IOException;
import java.io.StringReader;
import java.util.Arrays;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;

import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import server.db.DatabaseFunctor;
import server.db.StmtHelper;

import com.google.common.collect.Lists;

import feeds.FeedHelper;

public class PricesJob {
	public static String url()
	{
		return "http://www.zillow.com/webservice/GetUpdatedPropertyDetails.htm?zws-id="+ID+"&zpid=";
	}
	
	public DatabaseFunctor<Integer> getPrice(String zpid)
	{
		String result = FeedHelper.getServiceResult(url()+zpid);
		
		
		List<DatabaseFunctor<Integer>> inserts = Lists.newLinkedList();

		
		JSONObject obj = new JSONObject();
		SAXParserFactory parser = SAXParserFactory.newInstance();
		try {
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
			DocumentBuilder db = dbf.newDocumentBuilder();
			InputSource ins = new InputSource();
			ins.setCharacterStream(new StringReader(result));
			Document doc = db.parse(ins);
			doc.getDocumentElement().normalize();
		
			List<String> updateFields = Arrays.asList("price","status","type","mls","yearBuilt","yearUpdated","numFloors","basement","roof",
					"view","parkingType","heatingSources","heatingSystem","appliances","floorCovering","rooms","homeDescription","neighboorhood",
					"schoolDistrict","elementarySchool","middleSchool");
			StmtHelper setPrep = StmtHelper.db(" set ");
			for(String updateField : updateFields)
			{
				NodeList nodeLst = doc.getElementsByTagName(updateField);
				Node fieldNode = nodeLst.item(0);
				if(fieldNode!=null && fieldNode.getNodeType() == Node.ELEMENT_NODE)
				{
					Element fieldElem = (Element) fieldNode;
					if(fieldElem!=null && fieldElem.getTagName() !=null && fieldElem.getTagName().length()>1 && fieldElem.getTextContent()!=null && fieldElem.getTextContent().length()>1 )
					{
						String content = fieldElem.getTextContent().replaceAll("\t", "");
						setPrep.addSql(fieldElem.getTagName()+"=").addVariable(content);
						if(!updateFields.get(updateFields.size()-1).equals(updateField))
							setPrep.addSql(",");
					}
					 
				}
			}
			if( setPrep.getSql().toString().length()<7 || setPrep.getSql().toString().endsWith(","))
				setPrep.addSql("zillowID=").addVariable(zpid);
			
			
			
			 return db("update alllist").append(setPrep)
				.addSql(" where zillowID=").addVariable(zpid).executeUpdate();
			
		
		
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	private static String ID = "X1-ZWz1bwyrxi651n_7aoby";

	public void initializeScheduler() {
		// Creates a Scheduler instance.
		Scheduler getListingsFromZillow = new Scheduler();
		// Schedule a task to be run every night at mid-night
		//"00 00 * * 1-7"
		
		String id = getListingsFromZillow.schedule("20 * * * *", new Runnable() {
			public void run() {
				try {
					List<DatabaseFunctor<Integer>> insertList = Lists.newLinkedList();
					
					for(String zillowID : db("select zillowID from alllist").collectStrings.unsafeGet().get("zillowID") )
					{
						DatabaseFunctor priceFunc = getPrice(zillowID);
						if(priceFunc!=null)
							insertList.add(priceFunc);
					}
					DatabaseFunctor.sequence(insertList).unsafeUpdate();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		
		// Starts the scheduler.
		getListingsFromZillow.start();
		getListingsFromZillow.launch(getListingsFromZillow.getTask(id));
	}
	
	
}
